package com.chinaunicom.structure.flyweight;

import java.util.ArrayList;
import java.util.List;

/**
 * @author liry
 * @version 1.0
 * @date Created on 2022/8/10 15:03
 * Description:  Tree 的工厂模式
 */
public class TreeFactory {
    private static List<TreeType> cachePool = new ArrayList<>();

    public static TreeType createTree(String name, String color, String texture) {
        
        // 创建 TreeType
        TreeType treeType = getTreeByFeatures(name, color, texture);
        
        if (treeType == null){
            treeType = createTreeType(name, color, texture);
        }

        
        
        return treeType;
    }

    private static TreeType createTreeType(String name, String color, String texture) {
        TreeType treeType = new TreeType();
        treeType.setColor(color);
        treeType.setName(name);
        treeType.setTexture(texture);
        
        // 进行缓存
        cachePool.add(treeType);
        
        return treeType;
    }

    private static TreeType getTreeByFeatures(String name, String color, String texture) {
        if (cachePool != null && cachePool.size() > 0) {
            for (TreeType v : cachePool) {
                if (name.equals(v.getName()) && color.equals(v.getColor()) && texture.equals(v.getTexture())) {
                    return v;
                }
            }
        }
        return null;
    }
}
